package com.lening.organization.service.impl;

import com.lening.common.base.BaseServiceImpl;
import com.lening.organization.mapper.MenuMapper;
import com.lening.organization.dto.MenuDTO;
import com.lening.organization.po.Menu;
import com.lening.organization.service.MenuService;
import com.lening.organization.vo.MenuVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单栏 服务实现类
 * </p>
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<MenuMapper,Menu, MenuDTO> implements MenuService {

    @Override
    public List<MenuVo> leftMenu() {
        //1.查询菜单
        List<MenuVo> leftMenuList = this.baseMapper.getLeftMenu();

        //2.修改路由信息
        leftMenuList.forEach(item -> {
            if(StringUtils.hasText(item.getFile())){
                item.setFile(item.getFile().toLowerCase(Locale.ENGLISH).substring(0,item.getFile().length() -4));
            }
        });

        /*
         * 封装树形数据
         * leftMenuList.stream().collect(Collectors.groupingBy(LeftMenuVO::getParentId))
         *      1.groupingBy：对某个字段进行分组
         *      2.:: 方法引用
         *      3.groupByMap是什么数据？？
         *          key: parentId
         *          value: 根据parentId 进行分组后得到的集合数据
         * 循环赋值子菜单
         * 过滤，就是获取父菜单，因为父菜单中已经包含了子菜单
         */
        Map<Long, List<MenuVo>> groupByMap = leftMenuList.stream().collect(Collectors.groupingBy(MenuVo::getParentId));
        //leftMenuList.forEach(item -> item.setChildren(groupByMap.get(item.getId())));

        for (MenuVo vo : leftMenuList) {
            Long id = vo.getId();
            List<MenuVo> child = groupByMap.get(id);//根据key获取map里的value
            vo.setChildren(child);
        }

        leftMenuList.forEach(item -> item.setChildren(groupByMap.get(item.getId())));
        /*for (LeftMenuVO vo : leftMenuList) {
            vo.setChildren(groupByMap.get(vo.getId()));
        }*/
        return leftMenuList.stream().filter(item -> item.getParentId() == 0L).collect(Collectors.toList());
    }
}
